package edu.hubu.shop9.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.hubu.shop9.exception.MyException;
import edu.hubu.shop9.entity.Employee;
import edu.hubu.shop9.mapper.EmployeeMapper;
import edu.hubu.shop9.service.IEmployeeService;
import edu.hubu.shop9.vo.EmployeeVo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author waxijiang
 * @since 2021-07-26
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {
    @Autowired
    EmployeeMapper employeeMapper;

    @Override
    public IPage<EmployeeVo> selectByQuery(QueryWrapper<Employee> queryWrapper, Page<EmployeeVo> page) {
        return employeeMapper.specialSelectPage(page, queryWrapper);
    }

    @Override
    public Boolean checkUsername(String username) {
        Employee emp = employeeMapper.selectOne(new QueryWrapper<Employee>().eq("username", username));
        return emp == null;
    }

    @Override
    public Employee checkLogin(String username, String password) {
        Employee emp = employeeMapper.selectOne(new QueryWrapper<Employee>().eq("username", username));
        if (emp != null && !"".equals(password) && password.equals(emp.getPassword())) {
            return emp;
        }
        return null;
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public boolean batchImport(String fileName, MultipartFile file) throws IOException {
        boolean notNull = false;
        List<Employee> userList = new ArrayList<Employee>();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new MyException("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        if (sheet != null) {
            notNull = true;
        }
        Employee user;
        for (int r = 0; r <= Objects.requireNonNull(sheet).getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }

            user = new Employee();

            if (row.getCell(0).getCellType() != 1) {
                throw new MyException("导入失败(第" + (r + 1) + "行,用户请设为文本格式)");
            }
            String name = row.getCell(0).getStringCellValue();

            if (name == null || name.isEmpty()) {
                throw new MyException("导入失败(第" + (r + 1) + "行,用户名未填写)");
            }

            row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
            String password = row.getCell(1).getStringCellValue();
            if (password == null || password.isEmpty()) {
                throw new MyException("导入失败(第" + (r + 1) + "行,密码未填写)");
            }
            String email = row.getCell(2).getStringCellValue();
            if (email == null) {
                throw new MyException("导入失败(第" + (r + 1) + "行,邮箱未填写)");
            }

            String headImg = row.getCell(3).getStringCellValue();

            double age;
            if (row.getCell(4).getCellType() != Cell.CELL_TYPE_NUMERIC) {
                throw new MyException("导入失败(第" + (r + 1) + "行,年龄必须为数字)");
            } else {
                age = row.getCell(4).getNumericCellValue();
            }

            user.setUsername(name);
            user.setPassword(password);
            user.setHeadimage(headImg);
            user.setEmail(email);
            user.setAge((int) age);
            userList.add(user);
        }
        for (Employee userResord : userList) {
            String name = userResord.getUsername();
            Employee employee = employeeMapper.selectOne(new QueryWrapper<Employee>().eq("username", name));
            if (employee == null) {
                employeeMapper.insert(userResord);
                System.out.println(" 插入 " + userResord);
            } else {
                System.out.println(" 警告: " + userResord);
            }
        }
        return notNull;

    }
}
